﻿using System;
using System.Drawing;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using StedySoft.SenseSDK.DrawingCE;
using TimeTracker.Controls.ColorPickerForm.Base;

namespace SenseTimeTracker.CommonSenseControls
{
	public class SenseHSLColorPickerDialog : StedySoft.SenseSDK.ITranslucentForm
	{
		private Bitmap bitmap;

		protected override void OnPaint(System.Windows.Forms.PaintEventArgs e)
		{
			if (bitmap == null)
			{
				bitmap = GenerateBitmap();
			}

			e.Graphics.DrawImage(bitmap, 20, 20);
		}

		/// <summary>
		/// Generates the background image for the control
		/// </summary>
		/// <returns>The generated background image</returns>
		private Bitmap GenerateBitmap()
		{
			// width shall be multiple of 6, we have 3 base colors and 3 intermediate ones
			BitmapBuffer bitmapBuffer = new BitmapBuffer(360, 360);
			for (int i = 0; i < bitmapBuffer.Width; i++)
			{
				int color = 0;
				int z = bitmapBuffer.Width / 6;
				switch (i / z)
				{
					case 0:
						if (i % z == 0)
						{
							color = 255 << 16;
						}
						else
						{
							color = (255 << 16) + (((i % z) * 256 / z) - 1 << 8);
						}

						break;
					case 1:
						if (i % z == 0)
						{
							color = (255 << 16) + (255 << 8);
						}
						else
						{
							color = (((z - i % z) * 256 / z) - 1 << 16) + (255 << 8);
						}

						break;
					case 2:
						if (i % z == 0)
						{
							color = 255 << 8;
						}
						else
						{
							color = (255 << 8) + (((i % z) * 256 / z) - 1);
						}

						break;
					case 3:
						if (i % z == 0)
						{
							color = (255 << 8) + 255;
						}
						else
						{
							color = (((z - i % z) * 256 / z) - 1 << 8) + 255;
						}

						break;
					case 4:
						if (i % z == 0)
						{
							color = 255;
						}
						else
						{
							color = 255 + (((i % z) * 256 / z) - 1 << 16);
						}

						break;
					case 5:
						if (i % z == 0)
						{
							color = (255 << 16) + 255;
						}
						else
						{
							color = (((z - i % z) * 256 / z) - 1) + (255 << 16);
						}

						break;
				}

				for (int j = 0; j < bitmapBuffer.Height; j++)
				{
					int r = (int)Math.Round((((color & 0xff0000) >> 16) - 127.0) * (bitmapBuffer.Height - j - 1) / (bitmapBuffer.Height - 1) + 127.0);
					int g = (int)Math.Round((((color & 0x00ff00) >> 8) - 127.0) * (bitmapBuffer.Height - j - 1) / (bitmapBuffer.Height - 1) + 127.0);
					int b = (int)Math.Round(((color & 0x0000ff) - 127.0) * (bitmapBuffer.Height - j - 1) / (bitmapBuffer.Height - 1) + 127.0);
					bitmapBuffer[i, j] = (r << 16) + (g << 8) + b;
				}
			}

			return bitmapBuffer.CreateBitmap();
		}
	}
}
